package tech.aistar.corejava.day17.day17home;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 豆梦寒 on 2019/8/7.
 */
public class IEmpDaoImpl implements IEmpDao {
    private static boolean i = true;
    private List<Emp> list = new ArrayList<>();
    @Override
    public void save(Emp emp) {
        boolean flag = true;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals(emp)) {
                flag = false;
                System.out.println("员工已存在，勿重复添加");
                break;
            }
        }
        if(flag){
            list.add(emp);
        }
    }

    @Override
    public List<Emp> findAll() {
        if (i) {
            BufferedReader br = null;
            String line;
            String pathname="src/tech/aistar/corejava/day17home/emp.txt";
            File file = new File(pathname);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                br= new BufferedReader(new FileReader(pathname) {
                });

                while (true){

                    Emp emp = new Emp();

                    String[] s = null;

                    line=br.readLine();

                    if (line == null) {
                        break;
                    }
                    s=line.split("\\|");
                    if (s.length == 1) {
                        break;
                    }
                    emp.setEmpId(Integer.parseInt(s[1]));
                    emp.setEmpName(s[2]);
                    emp.setEmpBir(getDate(s[3]));
                    emp.setEmpJob(s[4]);
                }


            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            i = false;

        }

        return list;
    }

    private static Date getDate(String s){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
